/**
 * @program: LeetCode
 * @description: LeetCode :
 * @author: WXY
 * @create: 2022-12-25 15:35
 * @Version 1.0
 **/

public class offer_eight2_addTwoNumbers {
    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }


    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head1 = reverseList(l1);
        ListNode head2 = reverseList(l2);
        ListNode head = new ListNode(0);
        ListNode curHead = head;
        int c = 0; // 进位
        while (head1 != null && head2 != null) {
            int num = head1.val + head2.val + c;
            c = num / 10;
            head.next = new ListNode(num % 10);
            head = head.next;
            head1 = head1.next;
            head2 = head2.next;
        }
        while (head1 != null) {
            int num = head1.val + c;
            c = num / 10;
            head.next = new ListNode(num % 10);
            head = head.next;
            head1 = head1.next;
        }
        while (head2 != null) {
            int num = head2.val + c;
            c = num / 10;
            head.next = new ListNode(num % 10);
            head = head.next;
            head2 = head2.next;
        }
        if (c != 0) {
            head.next = new ListNode(c);
            head = head.next;
        }
        curHead = curHead.next;
        return reverseList(curHead);
    }


    private ListNode reverseList(ListNode head) {
        ListNode next = null;
        ListNode pre = null;
        while (head != null) {
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }
}

